package com.wxy.favorites;

import com.wxy.favorites.core.BizException;
import com.wxy.favorites.core.NoRollbackException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableAsync
@EnableScheduling
@EnableSwagger2
@Slf4j
public class Application {

    private static ConfigurableApplicationContext context;

    public static void main(String[] args) throws UnknownHostException {
        context = SpringApplication.run(Application.class, args);
        Environment environment = context.getBean(Environment.class);
        String path = Optional.ofNullable(environment.getProperty("server.servlet.context-path")).orElse("/");
        log.info("访问地址：http://{}:{}{}", InetAddress.getLocalHost().getHostAddress(),
                environment.getProperty("server.port"), path);
    }

    public static void restart(long delay) {
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(delay);
            } catch (InterruptedException e) {
                throw new NoRollbackException("服务重启失败");
            }
            ApplicationArguments args = context.getBean(ApplicationArguments.class);
            context.close();
            context = SpringApplication.run(Application.class, args.getSourceArgs());
        }).start();
    }

    public static void shutdown(long delay) {
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(delay);
            } catch (InterruptedException e) {
                throw new NoRollbackException("服务停止失败");
            }
            context.close();
        }).start();
    }
}

